<template>
  <div class="ed-form-fields">
    <el-row
      :gutter="20"
      class="top10"
    >
      <el-col
        :span="item.col"
        v-for="item in cols"
        :key="item.index"
      >
        <ed-form-field
          v-if="!item.disabled"
          :value="row[item.name]"
          v-bind="item.element"
          @change="onChange(item.name, $event)"
          :label-position="item.labelPosition"
        />
      </el-col>
      <slot />
    </el-row>
  </div>
</template>

<script>
import EdFormField from './EdFormField.vue'
import { getDefaultValue, isBlock } from '../../store/Form'

/**
 * 主要是数据收集的功能，数据项的增删是动态的
 */
export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Object,
      default: () => ({})
    },
    fields: {
      type: Array,
      default: () => []
    },
    labelPosition: {
      type: String,
      default: 'left'
    },
    span: {
      type: Number,
      default: 6
    }
  },
  data () {
    return {
      row: {}
    }
  },
  watch: {
    /**
     * 响应传入数据
     */
    value: {
      handler () {
        this.row = Object.assign({}, this.value)
      },
      deep: true
    }
  },
  created () {
    this.fields.map((field) => {
      const { name } = field
      if (this.value[name] === undefined) {
        this.$set(this.row, name, getDefaultValue(field))
      } else {
        this.$set(this.row, name, this.value[name])
      }
    })
  },
  components: {
    EdFormField
  },
  computed: {
    cols () {
      const vm = this
      // 记录所有的行
      // const _rows = []
      // 当前行
      let row = []
      // 保存当前行
      // _rows.push(row)
      // 当前行总列长
      // let cols = 0
      // 当前列长
      let col

      this.fields.forEach((element) => {
        // 当前元素的占位信息
        col = element.col || vm.span
        // 独占一行
        if (isBlock(element)) col = 24

        // 处理列信息
        // cols += col
        // 满载就新建，并记录当前列长
        // if (cols > 24) {
        //   row = []
        //   _rows.push(row)
        //   cols = col
        // }

        // 当前元素
        let item = {}
        // 压入当前元素
        row.push(item)

        item.col = col
        item.disabled = false
        item.name = element.name
        item.element = element
        if (element.when && element.when.name) {
          const v = vm.row[element.when.name]
          item.disabled = Array.isArray(element.when.value) ? element.when.value.includes(v) : element.when.value !== v
          // console.log(element.name, v, element.when.value, item.disabled)
        }

        if (item.disabled) this.$delete(this.row, name)

        item.labelPosition = item.element.labelPosition || this.labelPosition
      })

      return row
    }
  },
  methods: {
    onChange (name, value) {
      this.$emit('change', Object.assign({}, this.row, { [name]: value }))
    }
  }
}
</script>

<style scoped>
.ed-form-fields {
  padding-top: 20px;
}
.top10 {
  margin-top: 10px;
}
</style>
